// 全局变量
let scene, camera, renderer, raycaster, mouse;
let producers = [], consumers = [], decomposers = [];
let animationMixer, clock;
let isAnimating = false;

// 初始化场景
function init() {
    // 创建场景
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0x87CEEB); // 天空蓝
    
    // 创建相机
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.set(0, 5, 10);
    camera.lookAt(0, 0, 0);
    
    // 创建渲染器
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    
    document.getElementById('canvas-container').appendChild(renderer.domElement);
    
    // 创建光照
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
    scene.add(ambientLight);
    
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(10, 10, 5);
    directionalLight.castShadow = true;
    directionalLight.shadow.mapSize.width = 2048;
    directionalLight.shadow.mapSize.height = 2048;
    scene.add(directionalLight);
    
    // 创建湿地地形
    createWetland();
    
    // 创建生态系统元素
    createProducers();
    createConsumers();
    createDecomposers();
    
    // 创建射线检测器
    raycaster = new THREE.Raycaster();
    mouse = new THREE.Vector2();
    
    // 创建时钟
    clock = new THREE.Clock();
    
    // 添加事件监听
    window.addEventListener('resize', onWindowResize);
    renderer.domElement.addEventListener('click', onMouseClick);
    
    // 隐藏加载提示
    document.getElementById('loading').style.display = 'none';
}

// 创建湿地地形
function createWetland() {
    // 创建水面
    const waterGeometry = new THREE.PlaneGeometry(20, 20);
    const waterMaterial = new THREE.MeshPhongMaterial({ 
        color: 0x006994,
        transparent: true,
        opacity: 0.7
    });
    const water = new THREE.Mesh(waterGeometry, waterMaterial);
    water.rotation.x = -Math.PI / 2;
    water.position.y = -0.5;
    water.receiveShadow = true;
    scene.add(water);
    
    // 创建地面
    const groundGeometry = new THREE.PlaneGeometry(20, 20);
    const groundMaterial = new THREE.MeshPhongMaterial({ color: 0x8B4513 });
    const ground = new THREE.Mesh(groundGeometry, groundMaterial);
    ground.rotation.x = -Math.PI / 2;
    ground.position.y = -0.6;
    ground.receiveShadow = true;
    scene.add(ground);
}

// 创建生产者（水草）
function createProducers() {
    for (let i = 0; i < 5; i++) {
        const group = new THREE.Group();
        
        // 创建水草茎
        const stemGeometry = new THREE.CylinderGeometry(0.05, 0.05, 2);
        const stemMaterial = new THREE.MeshPhongMaterial({ color: 0x228B22 });
        const stem = new THREE.Mesh(stemGeometry, stemMaterial);
        stem.position.y = 1;
        stem.castShadow = true;
        group.add(stem);
        
        // 创建叶子
        for (let j = 0; j < 3; j++) {
            const leafGeometry = new THREE.SphereGeometry(0.3, 8, 6);
            const leafMaterial = new THREE.MeshPhongMaterial({ color: 0x006400 });
            const leaf = new THREE.Mesh(leafGeometry, leafMaterial);
            leaf.position.set(
                Math.random() * 0.5 - 0.25,
                1.5 + j * 0.3,
                Math.random() * 0.5 - 0.25
            );
            leaf.scale.set(1, 0.5, 1);
            leaf.castShadow = true;
            group.add(leaf);
        }
        
        group.position.set(
            Math.random() * 8 - 4,
            -0.5,
            Math.random() * 8 - 4
        );
        group.userData = { type: 'producer', name: '黑藻' };
        
        producers.push(group);
        scene.add(group);
    }
}

// 创建消费者（虾、鱼、白鹭）
function createConsumers() {
    // 创建虾
    for (let i = 0; i < 3; i++) {
        const shrimp = createShrimp();
        shrimp.position.set(
            Math.random() * 6 - 3,
            -0.3,
            Math.random() * 6 - 3
        );
        shrimp.userData = { type: 'consumer', name: '虾', level: '初级消费者' };
        consumers.push(shrimp);
        scene.add(shrimp);
    }
    
    // 创建鱼
    for (let i = 0; i < 2; i++) {
        const fish = createFish();
        fish.position.set(
            Math.random() * 4 - 2,
            0,
            Math.random() * 4 - 2
        );
        fish.userData = { type: 'consumer', name: '鱼', level: '次级消费者' };
        consumers.push(fish);
        scene.add(fish);
    }
    
    // 创建白鹭
    const egret = createEgret();
    egret.position.set(0, 3, 0);
    egret.userData = { type: 'consumer', name: '白鹭', level: '高级消费者' };
    consumers.push(egret);
    scene.add(egret);
}

// 创建虾模型
function createShrimp() {
    const group = new THREE.Group();
    
    // 身体
    const bodyGeometry = new THREE.SphereGeometry(0.2, 8, 6);
    const bodyMaterial = new THREE.MeshPhongMaterial({ color: 0xFF4500 });
    const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
    body.scale.set(1, 0.7, 1.5);
    group.add(body);
    
    // 尾巴
    const tailGeometry = new THREE.ConeGeometry(0.1, 0.3, 4);
    const tailMaterial = new THREE.MeshPhongMaterial({ color: 0xFF6347 });
    const tail = new THREE.Mesh(tailGeometry, tailMaterial);
    tail.position.z = 0.3;
    tail.rotation.x = Math.PI / 2;
    group.add(tail);
    
    return group;
}

// 创建鱼模型
function createFish() {
    const group = new THREE.Group();
    
    // 身体
    const bodyGeometry = new THREE.SphereGeometry(0.3, 8, 6);
    const bodyMaterial = new THREE.MeshPhongMaterial({ color: 0x4169E1 });
    const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
    body.scale.set(1, 0.6, 2);
    group.add(body);
    
    // 尾巴
    const tailGeometry = new THREE.ConeGeometry(0.2, 0.4, 4);
    const tailMaterial = new THREE.MeshPhongMaterial({ color: 0x1E90FF });
    const tail = new THREE.Mesh(tailGeometry, tailMaterial);
    tail.position.z = 0.8;
    tail.rotation.x = Math.PI / 2;
    group.add(tail);
    
    return group;
}

// 创建白鹭模型
function createEgret() {
    const group = new THREE.Group();
    
    // 身体
    const bodyGeometry = new THREE.SphereGeometry(0.4, 8, 6);
    const bodyMaterial = new THREE.MeshPhongMaterial({ color: 0xFFFFFF });
    const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
    group.add(body);
    
    // 头部
    const headGeometry = new THREE.SphereGeometry(0.2, 8, 6);
    const headMaterial = new THREE.MeshPhongMaterial({ color: 0xFFFFFF });
    const head = new THREE.Mesh(headGeometry, headMaterial);
    head.position.set(0.3, 0.2, 0);
    group.add(head);
    
    // 喙
    const beakGeometry = new THREE.ConeGeometry(0.05, 0.3, 4);
    const beakMaterial = new THREE.MeshPhongMaterial({ color: 0xFFD700 });
    const beak = new THREE.Mesh(beakGeometry, beakMaterial);
    beak.position.set(0.5, 0.2, 0);
    beak.rotation.z = Math.PI / 2;
    group.add(beak);
    
    // 翅膀
    const wingGeometry = new THREE.PlaneGeometry(1, 0.3);
    const wingMaterial = new THREE.MeshPhongMaterial({ 
        color: 0xFFFFFF,
        side: THREE.DoubleSide
    });
    const wing = new THREE.Mesh(wingGeometry, wingMaterial);
    wing.position.set(0, 0.2, 0);
    group.add(wing);
    
    return group;
}

// 创建分解者（细菌、真菌）
function createDecomposers() {
    for (let i = 0; i < 10; i++) {
        const particleGeometry = new THREE.SphereGeometry(0.05, 4, 4);
        const particleMaterial = new THREE.MeshPhongMaterial({ 
            color: 0x8B4513,
            transparent: true,
            opacity: 0.7
        });
        const particle = new THREE.Mesh(particleGeometry, particleMaterial);
        
        particle.position.set(
            Math.random() * 10 - 5,
            -0.4,
            Math.random() * 10 - 5
        );
        particle.userData = { type: 'decomposer', name: '细菌/真菌' };
        
        decomposers.push(particle);
        scene.add(particle);
    }
}

// 鼠标点击事件
function onMouseClick(event) {
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
    
    raycaster.setFromCamera(mouse, camera);
    
    const allObjects = [...producers, ...consumers, ...decomposers];
    const intersects = raycaster.intersectObjects(allObjects, true);
    
    if (intersects.length > 0) {
        const clickedObject = intersects[0].object.parent || intersects[0].object;
        
        if (clickedObject.userData.type === 'producer') {
            showInfoPanel('生产者：黑藻', '通过光合作用制造有机物，为其他生物提供能量，是生态系统的基础。');
        } else if (clickedObject.userData.type === 'consumer') {
            if (!isAnimating) {
                showFoodChain();
            }
        } else if (clickedObject.userData.type === 'decomposer') {
            showInfoPanel('分解者：细菌/真菌', '分解动植物遗体，将有机物转化为无机物(如二氧化碳、无机盐)，回归土壤和大气供生产者重新利用，完成物质循环。');
        }
    }
}

// 显示信息面板
function showInfoPanel(title, content) {
    const panel = document.getElementById('info-panel');
    document.getElementById('info-title').textContent = title;
    document.getElementById('info-content').textContent = content;
    panel.style.display = 'block';
}

// 关闭信息面板
function closeInfoPanel() {
    document.getElementById('info-panel').style.display = 'none';
}

// 显示食物链动画
function showFoodChain() {
    isAnimating = true;
    document.getElementById('food-chain').style.display = 'block';
    
    // 获取相关对象
    const plant = producers[0];
    const shrimp = consumers.find(c => c.userData.name === '虾');
    const fish = consumers.find(c => c.userData.name === '鱼');
    const egret = consumers.find(c => c.userData.name === '白鹭');
    
    // 动画序列
    animateFoodChain(plant, shrimp, fish, egret);
}

// 关闭食物链
function closeFoodChain() {
    document.getElementById('food-chain').style.display = 'none';
    isAnimating = false;
    
    // 重置位置
    resetPositions();
}

// 食物链动画
function animateFoodChain(plant, shrimp, fish, egret) {
    const duration = 2000;
    
    // 虾游向水草
    animateObject(shrimp, plant.position, duration, () => {
        // 鱼游向虾
        animateObject(fish, shrimp.position, duration, () => {
            // 白鹭俯冲捕鱼
            animateObject(egret, fish.position, duration, () => {
                setTimeout(() => {
                    closeFoodChain();
                }, 1000);
            });
        });
    });
}

// 对象动画
function animateObject(object, targetPosition, duration, callback) {
    const startPosition = object.position.clone();
    const startTime = Date.now();
    
    function animate() {
        const elapsed = Date.now() - startTime;
        const progress = Math.min(elapsed / duration, 1);
        
        object.position.lerpVectors(startPosition, targetPosition, progress);
        
        if (progress < 1) {
            requestAnimationFrame(animate);
        } else if (callback) {
            callback();
        }
    }
    
    animate();
}

// 重置位置
function resetPositions() {
    // 重置虾的位置
    consumers.filter(c => c.userData.name === '虾').forEach((shrimp, i) => {
        shrimp.position.set(
            Math.random() * 6 - 3,
            -0.3,
            Math.random() * 6 - 3
        );
    });
    
    // 重置鱼的位置
    consumers.filter(c => c.userData.name === '鱼').forEach((fish, i) => {
        fish.position.set(
            Math.random() * 4 - 2,
            0,
            Math.random() * 4 - 2
        );
    });
    
    // 重置白鹭的位置
    const egret = consumers.find(c => c.userData.name === '白鹭');
    if (egret) {
        egret.position.set(0, 3, 0);
    }
}

// 窗口大小调整
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}

// 动画循环
function animate() {
    requestAnimationFrame(animate);
    
    // 水草摆动
    producers.forEach((producer, index) => {
        producer.rotation.z = Math.sin(Date.now() * 0.001 + index) * 0.1;
    });
    
    // 分解者粒子浮动
    decomposers.forEach((decomposer, index) => {
        decomposer.position.y = -0.4 + Math.sin(Date.now() * 0.002 + index) * 0.05;
    });
    
    // 虾游动
    consumers.filter(c => c.userData.name === '虾').forEach((shrimp, index) => {
        if (!isAnimating) {
            shrimp.position.x += Math.sin(Date.now() * 0.001 + index) * 0.01;
            shrimp.position.z += Math.cos(Date.now() * 0.001 + index) * 0.01;
        }
    });
    
    // 鱼游动
    consumers.filter(c => c.userData.name === '鱼').forEach((fish, index) => {
        if (!isAnimating) {
            fish.position.x += Math.sin(Date.now() * 0.0008 + index) * 0.02;
            fish.position.z += Math.cos(Date.now() * 0.0008 + index) * 0.02;
        }
    });
    
    // 白鹭盘旋
    const egret = consumers.find(c => c.userData.name === '白鹭');
    if (egret && !isAnimating) {
        egret.position.x = Math.sin(Date.now() * 0.0005) * 3;
        egret.position.z = Math.cos(Date.now() * 0.0005) * 3;
    }
    
    renderer.render(scene, camera);
}

// 初始化并开始动画
init();
animate();
